package com.jzy.gulimall.order.web;

import com.jzy.common.exception.BizCodeEnum;
import com.jzy.common.exception.NoStockException;
import com.jzy.gulimall.order.service.OrderService;
import com.jzy.gulimall.order.vo.OrderConfirmVo;
import com.jzy.gulimall.order.vo.OrderRespVo;
import com.jzy.gulimall.order.vo.OrderSubmitVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @author jzy
 * @date 2020/9/20 15:40
 */
@Controller
public class OrderWebController {

    @Resource
    private OrderService orderService;

    /**
     * 提交订单  生成订单
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes attributes) {
        //创建订单,校验令牌,校验价格,锁库存
        OrderRespVo orderRespVo = null;
        try {
            orderRespVo = orderService.submitOrder(orderSubmitVo);
            if (orderRespVo.getCode() == 0) {
                //下单成功去到支付选择页
                model.addAttribute("orderRespVo", orderRespVo);
                return "pay";
            } else {
                //下单失败回到订单确认页
                //令牌验证失败 价格校验失败
                attributes.addAttribute("msg", BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (NoStockException e) {
            //库存不够
            attributes.addAttribute("msg", e.getMsg());
            e.printStackTrace();
        } catch (Exception e) {
            //构造订单出错
            attributes.addAttribute("msg", BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
            e.printStackTrace();
        }
        return "redirect:http://order.gulimall.com/toTrade";
    }


    /**
     * 订单确认页
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        if (orderConfirmVo != null) {
            model.addAttribute("confirm", orderConfirmVo);
            return "confirm";
        }
        return "redirect:http://gulimall.com";
    }
}
